package com.stk.sinous;

import java.util.Random;

import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.opengl.util.GLState;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

public class Rock extends Rectangle{
	private final PhysicsHandler physicsHandler;
	private float speed = 90.0f;
	private int width;
	private int height;
	private SinousActivity sActivity;
	
	public Rock(float pX, float pY, float pWidth, float pHeight, VertexBufferObjectManager vertexBufferObjectManager, int width, int height, SinousActivity sa) {
		super(pX, pY, pWidth, pHeight, vertexBufferObjectManager);
		this.physicsHandler = new PhysicsHandler(this);
        this.registerUpdateHandler(this.physicsHandler);
        this.physicsHandler.setVelocity(speed, speed);
        
        this.width = width;
        this.height = height;
        
        this.sActivity = sa;
        
        this.setColor(204/255f,0/255f,0/255f);
        
        Random rand = new Random();
        this.registerEntityModifier(new LoopEntityModifier(new RotationModifier(rand.nextInt(10) + 10, 0, (rand.nextBoolean()?1:-1) + 360)));
	}
	
	@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {
		if (sActivity.getMoves() % 50 == 0) {
			speed +=5;
		}
		Random rand = new Random();
		if(this.getX() > width || this.getY() > height) {
			float realSpeed = speed + rand.nextInt(20);
			this.physicsHandler.setVelocity(realSpeed, realSpeed);
			if (rand.nextBoolean()){
				this.setPosition(rand.nextInt(width) - width/2, -rand.nextInt(height/2));
			}else{
				this.setPosition(-rand.nextInt(width) - width/2, rand.nextInt(height/2));
			}
			
		}

		super.onManagedUpdate(pSecondsElapsed);
	}

	@Override
	protected void applyRotation(GLState pGLState) {
		final float rotation = this.mRotation;

		if(rotation != 0) {
			final float rotationCenterX = this.mRotationCenterX;
			final float rotationCenterY = this.mRotationCenterY;

			pGLState.translateModelViewGLMatrixf(rotationCenterX, rotationCenterY, 0);
			/* Note we are applying rotation around the y-axis and not the z-axis anymore! */
			pGLState.rotateModelViewGLMatrixf(rotation, 0, 0, 1);
			pGLState.translateModelViewGLMatrixf(-rotationCenterX, -rotationCenterY, 0);
		}
	}
	
	
}
